package com.zl.learning.thread.thread_daemon;

import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created by zhaolei on 2017/6/20.
 */
public class CallableTest {

    @Test
    public void test1(){
        FutureTask<Integer> task = new FutureTask<Integer>(new RtThread());
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName()+"mainThread:"+i);
            if(i==20){
                new Thread(task).start();
            }
        }
        try {
            System.out.println("subThread return:"+task.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2(){
        FutureTask<Integer> task = new FutureTask<>(() -> {
            int sum = 0;
            for (int i = 0; i < 100; i++) {
                sum += i;
                Thread.sleep(100);
            }
            return sum;
        });
        new Thread(task).start();
        System.out.println("Thread start");
        try {
            System.out.println("subThread return:"+task.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static class RtThread implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            int sum = 0;
            for(int i=0;i<100;i++){
    //            System.out.println(Thread.currentThread().getName()+"subThread:"+i);
                sum+=i;
                Thread.sleep(100);
            }
            return sum;
        }
    }
}

